import type { NavigationGuardNext, RouteLocationNormalized, Router } from "vue-router";
import utils from "@/utils/"
import { CacheEnum } from "@/enum/cacheEnum";
import menuStore from "@/store/menuStore";


//定义路由守卫类
class Guard {
  constructor(private router: Router) {

  }

  private isRoutesLoaded = false

  public run() {
    this.router.beforeEach(this.beforeEach.bind(this))
  }


  private beforeEach(to: RouteLocationNormalized, from: RouteLocationNormalized, next:NavigationGuardNext) {

    //验证用户是否登录
    if (this.isLogin(to) === false) next({ name: 'login' }) 
    //验证用户是否为游客
    else if (this.isGuest(to) === false) next(from) 
    
    else{
      next()
    }
  
    
    //await this.getUserInfo()

  }

  /**
   * 获取用户资料
   */
  // private getUserInfo(){
  //   if(this.token()) userStore().getUserInfo()
  // }

  /**
   * 
   * 获取浏览器中保存的token
   */
  private token(): string | null {
    return utils.store.get(CacheEnum.TOKEN_NAME)?.token
  }

  /**
   * 对当前路由进行检测，判断用户是否已经登录
   * @param route(当前路由，类型：RouteLocationNormalized) 
   * @returns true 用户已经登录
   *       false 用户未登录
   */
  private isLogin(route: RouteLocationNormalized): boolean {

    const state = Boolean(!route.meta.auth || (route.meta.auth && this.token()))
    if (state === false) {
      utils.store.set(CacheEnum.REDIRECT_ROUTE_NAME, route.name)
    }
    return state
  }
  /**
  * 对当前路由进行检测，判断用户是否为游客
  * @param route(当前路由，类型：RouteLocationNormalized) 
  * @returns true ,用户未登录或登录已过期
  *       false ,用户为游客
  */
  private isGuest(route: RouteLocationNormalized): boolean {
    return Boolean(!route.meta.guest || (route.meta.guest && !this.token()))
  }
  /**
    * 该函数对当前路由进行检测，判断用户是否具有访问权限(暂未实现)
    * @param route(当前路由，类型：RouteLocationNormalized) 
    * @returns：true ,用户有访问权限
    *       false ,用户无访问权限
    */

}

export default (router: Router) => {
  new Guard(router).run()
}